package com.reebake.ideal.infra.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reebake.ideal.infra.entity.DataDict;
import com.reebake.ideal.infra.entity.DataDictItem;
import com.reebake.ideal.infra.service.DataDictItemService;
import com.reebake.ideal.infra.service.DataDictService;
import com.reebake.ideal.infra.vo.DataDictTreeModel;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RequiredArgsConstructor
@RestController
@RequestMapping("/data/dict")
public class DataDictPlusController {
    private final DataDictService dataDictService;
    private final DataDictItemService dataDictItemService;

    private List<DataDict> queryDict() {
        LambdaQueryWrapper<DataDict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(DataDict::getOrderNo);

        return dataDictService.list(queryWrapper);
    }

    private List<DataDictItem> queryDictItem() {
        LambdaQueryWrapper<DataDictItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(DataDictItem::getOrderNo);

        return dataDictItemService.list(queryWrapper);
    }

    @GetMapping("all-tree")
    public List<DataDictTreeModel> all() {
        List<DataDictTreeModel> roots = new ArrayList<>();

        List<DataDict> dictList = queryDict();
        List<DataDictItem> dictItemList = queryDictItem();
        for(DataDict dataDict : dictList) {
            DataDictTreeModel root = treeNode(dataDict);
            tree(root, dictItemList);
            roots.add(root);
        }
        return roots;
    }

    private DataDictTreeModel treeNode(DataDict dataDict) {
        DataDictTreeModel treeNode = new DataDictTreeModel();
        treeNode.setValue(dataDict.getDictCode());
        treeNode.setLabel(dataDict.getDictName());

        return treeNode;
    }

    private DataDictTreeModel treeNode(DataDictItem dataDictItem) {
        DataDictTreeModel treeNode = new DataDictTreeModel();
        treeNode.setValue(dataDictItem.getDataCode());
        treeNode.setLabel(dataDictItem.getDataName());

        return treeNode;
    }

    private void tree(DataDictTreeModel parent, List<DataDictItem> data) {
        for(DataDictItem dataDictItem : data) {
            if(dataDictItem.getDictCode().equals(parent.getValue())) {
                parent.getChildren().add(treeNode(dataDictItem));
            }
        }
        if(CollectionUtil.isEmpty(parent.getChildren())) {
            return;
        }
        for(DataDictTreeModel treeNode : parent.getChildren()) {
            tree(treeNode, data);
        }
    }
}
